<template>
    <view class="login-container">
        <!-- 背景装饰 -->
        <view class="bg-decoration"></view>
        
        <!-- 登录卡片 -->
        <view class="login-card">
            <!-- 应用Logo -->
            <view class="logo-wrapper">
                <text class="app-title">现场验收管理平台</text>
            </view>
            
            <!-- 登录表单 -->
            <view class="form-wrapper">
                <view class="input-group">
                    <view class="input-icon">
                        <text class="fa fa-user">账号</text>
                    </view>
                    <input 
                        type="text" 
                        v-model="form.username" 
                        placeholder="请输入用户名" 
                        placeholder-class="placeholder-style"
                        class="login-input"
                    />
                </view>
                
                <view class="input-group">
                    <view class="input-icon">
                        <text class="fa fa-lock">密码</text>
                    </view>
                    <input 
                        type="password" 
                        v-model="form.password" 
                        placeholder="请输入密码" 
                        placeholder-class="placeholder-style"
                        class="login-input"
                    />
                </view>
                
                <!-- 错误提示 -->
                <view class="error-tip" v-if="errorMessage">{{ errorMessage }}</view>
                
                <!-- 登录按钮 -->
                <button 
                    class="login-button" 
                    :loading="loading" 
                    :disabled="loading"
                    @click="handleLogin"
                >
                    {{ loading ? '登录中...' : '登录' }}
                </button>
                
                <!-- 其他选项 -->
                <view class="options-wrapper">
                    <text class="option-item" @click="showChangePwdModal">修改密码</text>
                </view>
            </view>
        </view>
        
        <!-- 底部信息 -->
        <view class="footer-info">
            <text>© 2025 版权所有</text>
        </view>
        
        <!-- 修改密码模态框 -->
        <view class="modal-mask" v-if="showModal" @click.stop>
            <view class="modal-container">
                <view class="modal-header">
                    <text class="modal-title">修改密码</text>
                    <text class="close-icon" @click="hideChangePwdModal">×</text>
                </view>
                <view class="modal-body">
                    <view class="modal-form">
                        <view class="modal-input-group">
                            <view class="input-label">手机号码</view>
                            <view class="input-row">
                                <input 
                                    type="text" 
                                    v-model="changePwdForm.phone" 
                                    placeholder="请输入注册手机号" 
                                    class="modal-input"
                                    @blur="validatePhone"
                                />
                                <button 
                                    class="verify-code-btn" 
                                    :disabled="!canSendCode || sendingCode"
                                    @click="sendVerifyCode"
                                >
                                    {{ sendingCode ? countdown + 's' : canSendCode ? '获取验证码' : '请输入手机号' }}
                                </button>
                            </view>
                            <view class="error-message" v-if="changePwdForm.errors.phone">{{ changePwdForm.errors.phone }}</view>
                        </view>
                        
                        <view class="modal-input-group">
                            <view class="input-label">原密码</view>
                            <input 
                                type="password" 
                                v-model="changePwdForm.oldPassword" 
                                placeholder="请输入原密码" 
                                class="modal-input"
                                @blur="validateOldPassword"
                            />
                            <view class="error-message" v-if="changePwdForm.errors.oldPassword">{{ changePwdForm.errors.oldPassword }}</view>
                        </view>
                        
                        <view class="modal-input-group">
                            <view class="input-label">新密码</view>
                            <input 
                                type="password" 
                                v-model="changePwdForm.newPassword" 
                                placeholder="请输入新密码" 
                                class="modal-input"
                                @blur="validateNewPassword"
                            />
                            <view class="error-message" v-if="changePwdForm.errors.newPassword">{{ changePwdForm.errors.newPassword }}</view>
                        </view>
                        
                        <view class="modal-input-group">
                            <view class="input-label">验证码</view>
                            <input 
                                type="text" 
                                v-model="changePwdForm.verifyCode" 
                                placeholder="请输入验证码" 
                                class="modal-input"
                                @blur="validateVerifyCode"
                            />
                            <view class="error-message" v-if="changePwdForm.errors.verifyCode">{{ changePwdForm.errors.verifyCode }}</view>
                        </view>
                    </view>
                </view>
                <view class="modal-footer">
                    <button class="modal-confirm-btn" @click="submitChangePassword">确认修改</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

// 从本地存储获取token并检查登录状态
const token = uni.getStorageSync("userInfo")?.token;
if (token) {
    uni.request({
        url: './api/ct',
        method: 'GET',
        header: {
            'Authorization': `Bearer ${token}`
        },
        success: (res) => {
            if (res.statusCode === 200 && res.data.message === "合法") {
                uni.redirectTo({
                    url: "/pages/index/index",
                });
            }
        }
    })
}

// 登录表单数据
const form = reactive({
    username: '',
    password: ''
})

// 登录状态管理
const loading = ref(false)
const errorMessage = ref('')

// 修改密码模态框状态
const showModal = ref(false)
const sendingCode = ref(false)
const countdown = ref(60)
const canSendCode = ref(true)

// 修改密码表单数据
const changePwdForm = reactive({
    phone: '',
    oldPassword: '',
    newPassword: '',
    verifyCode: '',
    errors: {
        phone: '',
        oldPassword: '',
        newPassword: '',
        verifyCode: ''
    }
})

// 登录处理函数
const handleLogin = async () => {
    // 表单验证
    if (!form.username.trim()) {
        errorMessage.value = '请输入用户名'
        return
    }
    
    if (!form.password.trim()) {
        errorMessage.value = '请输入密码'
        return
    }
    
    // 清空错误信息
    errorMessage.value = ''
    loading.value = true
    
    try {
        // 发送登录请求
        const res = await uni.request({
            url: './api/weblogin',
            method: 'GET',
            data: {
                username: form.username,
                password: form.password
            }
        })
        
        // 处理响应
        if (res.statusCode === 200 && res.data.message === '登录成功') {
            // 保存用户信息到本地存储
            uni.setStorageSync('userInfo', {
                name: res.data.name,
                token: res.data.access_token,
                role: res.data.role
            })
            
            // 显示成功提示（使用uni原生API）
            uni.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 2000
            })
            
            uni.navigateTo({ url: '/pages/index/index' })
        } else {
            errorMessage.value = res.data.message || '登录失败，请重试'
        }
    } catch (error) {
        console.error('登录请求失败:', error)
        errorMessage.value = '网络请求失败，请检查网络连接'
    } finally {
        loading.value = false
    }
}

// 显示修改密码模态框
const showChangePwdModal = () => {
    // 重置表单数据
    resetChangePwdForm()
    showModal.value = true
}

// 隐藏修改密码模态框
const hideChangePwdModal = () => {
    showModal.value = false
}

// 重置修改密码表单
const resetChangePwdForm = () => {
    changePwdForm.phone = ''
    changePwdForm.oldPassword = ''
    changePwdForm.newPassword = ''
    changePwdForm.verifyCode = ''
    changePwdForm.errors = {
        phone: '',
        oldPassword: '',
        newPassword: '',
        verifyCode: ''
    }
    canSendCode.value = true
    sendingCode.value = false
    countdown.value = 60
}

// 验证手机号码
const validatePhone = () => {
    const phone = changePwdForm.phone.trim()
    if (!phone) {
        changePwdForm.errors.phone = '请输入手机号码'
        return false
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        changePwdForm.errors.phone = '请输入正确的手机号码'
        return false
    }
    changePwdForm.errors.phone = ''
    canSendCode.value = true
    return true
}

// 验证原密码
const validateOldPassword = () => {
    const oldPassword = changePwdForm.oldPassword.trim()
    if (!oldPassword) {
        changePwdForm.errors.oldPassword = '请输入原密码'
        return false
    }
    if (oldPassword.length < 6) {
        changePwdForm.errors.oldPassword = '密码长度不能少于6位'
        return false
    }
    changePwdForm.errors.oldPassword = ''
    return true
}

// 验证新密码
const validateNewPassword = () => {
    const newPassword = changePwdForm.newPassword.trim()
    if (!newPassword) {
        changePwdForm.errors.newPassword = '请输入新密码'
        return false
    }
    if (newPassword.length < 6) {
        changePwdForm.errors.newPassword = '密码长度不能少于6位'
        return false
    }
    if (newPassword === changePwdForm.oldPassword) {
        changePwdForm.errors.newPassword = '新密码不能与原密码相同'
        return false
    }
    changePwdForm.errors.newPassword = ''
    return true
}

// 验证验证码
const validateVerifyCode = () => {
    const verifyCode = changePwdForm.verifyCode.trim()
    if (!verifyCode) {
        changePwdForm.errors.verifyCode = '请输入验证码'
        return false
    }
    if (verifyCode.length !== 6) {
        changePwdForm.errors.verifyCode = '验证码应为6位数字'
        return false
    }
    changePwdForm.errors.verifyCode = ''
    return true
}

// 发送验证码
const sendVerifyCode = () => {
    if (!validatePhone()) return
    
        sendingCode.value = true
        canSendCode.value = false
        
        // 发送验证码请求
        uni.request({
            url: './api/sendVerifyCode/' + changePwdForm.phone,
            method: 'POST',
            data: {
                phone: changePwdForm.phone,
                type: 'changePassword' // 验证码类型
            },
            success(res) {
                if (res.statusCode === 200 && res.data.message.includes('验证码已发送')) {
                    uni.showToast({
                        title: '验证码发送成功',
                        icon: 'success',
                        duration: 2000
                    })

                    startCountdown()
                } else {
                    uni.showToast({
                        title: res.data.message || '验证码发送失败',
                        icon: 'none',
                        duration: 2000
                    })
                    canSendCode.value = true
                    sendingCode.value = false
                }
            }
        })
    }
       

// 倒计时
const startCountdown = () => {
    let timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(timer)
            canSendCode.value = true
            sendingCode.value = false
            countdown.value = 60
        }
    }, 1000)
}

// 提交修改密码
const submitChangePassword = () => {
    // 表单验证
    if (!validatePhone()) return
    if (!validateOldPassword()) return
    if (!validateNewPassword()) return
    if (!validateVerifyCode()) return
    
    try {
        uni.request({
            url: './api/changePassword',
            method: 'POST',
            data: {
                phone: changePwdForm.phone,
                oldPassword: changePwdForm.oldPassword,
                newPassword: changePwdForm.newPassword,
                verifyCode: changePwdForm.verifyCode
            }
        })
        
        if (res.statusCode === 200 && res.data.message.includes('成功')) {
            uni.showToast({
                title: '密码修改成功',
                icon: 'success',
                duration: 2000
            })
            hideChangePwdModal()
        } else {
            uni.showToast({
                title: res.data.message || '密码修改失败',
                icon: 'none',
                duration: 2000
            })
        }
    } catch (error) {
        console.error('修改密码失败:', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none',
            duration: 2000
        })
    }
}
</script>

<style>
/* 样式部分与之前一致，无需修改 */

.fa {
    font-family: 'FontAwesome';
}

.login-container {
    display: flex;
    flex-direction: column;
    height: 95vh;
    background-color: #f5f7fa;
    position: relative;
    overflow: hidden;
}

.modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-container {
    background-color: #fff;
    border-radius: 16rpx;
    width: 80%;
    max-width: 700rpx;
    overflow: hidden;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1rpx solid #eee;
}

.modal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.close-icon {
    font-size: 40rpx;
    color: #999;
    cursor: pointer;
}

.modal-body {
    padding: 30rpx 40rpx;
}

.modal-form {
    width: 100%;
}

.modal-input-group {
    margin-bottom: 30rpx;
}

.input-label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 15rpx;
}

.input-row {
    display: flex;
    align-items: center;
}

.modal-input {
    flex: 1;
    height: 80rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
}

.verify-code-btn {
    width: 200rpx;
    height: 80rpx;
    background-color: #1488CC;
    color: #fff;
    font-size: 24rpx;
    border-radius: 8rpx;
    margin-left: 20rpx;
    padding: 0;
}

.error-message {
    color: #f56c6c;
    font-size: 24rpx;
    margin-top: 10rpx;
}

.modal-footer {
    padding: 20rpx 40rpx 40rpx;
    display: flex;
    justify-content: center;
}

.modal-confirm-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #1488CC, #2B32B2);
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
    box-shadow: 0 6rpx 20rpx rgba(20, 136, 204, 0.3);
}

.bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 35vh;
    background: linear-gradient(135deg, #1488CC, #2B32B2);
    border-radius: 0 0 50% 50% / 0 0 20% 20%;
    transform: scaleX(1.5);
    z-index: 0;
}

.login-card {
    width: 85%;
    max-width: 600rpx;
    background-color: #fff;
    border-radius: 24rpx;
    box-shadow: 0 10rpx 50rpx rgba(0, 0, 0, 0.1);
    margin: auto;
    margin-top: 30vh;
    padding: 60rpx 40rpx;
    position: relative;
    z-index: 1;
}

.logo-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;
}

.app-title {
    font-size: 56rpx;
    font-weight: bold;
    color: #333;
    letter-spacing: 2rpx;
}

.form-wrapper {
    width: 100%;
}

.input-group {
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #eee;
    padding: 20rpx 0;
    margin-bottom: 10rpx;
}

.input-icon {
    width: 60rpx;
    text-align: center;
    font-size: 28rpx;
    color: #999;
}

.login-input {
    flex: 1;
    height: 60rpx;
    font-size: 28rpx;
    padding-left: 20rpx;
    color: #333;
}

.placeholder-style {
    color: #ccc;
}

.error-tip {
    color: #f56c6c;
    font-size: 24rpx;
    text-align: center;
    padding: 20rpx 0;
    min-height: 30rpx;
}

.login-button {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #1488CC, #2B32B2);
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
    margin-top: 20rpx;
    box-shadow: 0 6rpx 20rpx rgba(20, 136, 204, 0.3);
}

.options-wrapper {
    display: flex;
    justify-content: space-between;
    margin-top: 40rpx;
}

.option-item {
    font-size: 24rpx;
    color: #666;
    cursor: pointer;
}

.footer-info {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 22rpx;
}
</style>